using System;
using System.IO;
using System.Threading;
using System.Web;
using System.Xml.Linq;
using Coderoom.ScrumPlanner.Configuration;

namespace Coderoom.ScrumPlanner.Data.Repositories.Xml
{
	public abstract class XmlRepository : Repository
	{
		#region State

		private readonly ReaderWriterLockSlim _lock;

		#endregion

		protected XmlRepository()
		{
			_lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
		}

		public abstract string DataFileName { get; }

		protected ReaderWriterLockSlim Lock
		{
			get { return _lock; }
		}

		protected XDocument ReadXml()
		{
			var dataDirectoryPath = ConfigurationManager.GetXmlRepositoryDataDirectoryPath();

			if (dataDirectoryPath.StartsWith("~", StringComparison.OrdinalIgnoreCase))
			{
				// this is a web app
				return XDocument.Load(HttpContext.Current.Server.MapPath(dataDirectoryPath + DataFileName));
			}

			// this is not a web app
			return XDocument.Load(Path.Combine(dataDirectoryPath, DataFileName));
		}

		protected void WriteXml(XDocument xml)
		{
			var dataDirectoryPath = ConfigurationManager.GetXmlRepositoryDataDirectoryPath();

			if (dataDirectoryPath.StartsWith("~", StringComparison.OrdinalIgnoreCase))
			{
				// this is a web app
				xml.Save(HttpContext.Current.Server.MapPath(dataDirectoryPath + DataFileName));
				return;
			}

			// this is not a web app
			xml.Save(Path.Combine(ConfigurationManager.GetXmlRepositoryDataDirectoryPath(), DataFileName));
		}

		#region Base class overrides

		protected override void Dispose(bool disposing)
		{
			if (disposing)
				_lock.Dispose();

			base.Dispose(disposing);
		}

		#endregion
	}
}